package com.twan.kotlinbase.app

import android.app.Activity
import android.app.Application
import android.os.Process
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMSDKConfig
import com.tencent.imsdk.v2.V2TIMSDKListener
import com.tencent.qcloud.tim.demo.DemoApplication
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.config.CustomFaceConfig
import com.tencent.qcloud.tim.uikit.config.GeneralConfig
import com.twan.kotlinbase.ui.LoginActivity
import com.twan.kotlinbase.util.MyUtils
import com.twan.kotlinbase.widgets.router.Router
import com.umeng.commonsdk.UMConfigure
import rxhttp.wrapper.param.RxHttp
import kotlin.system.exitProcess

class App : Application() {

    companion object {
        private var allActivities = mutableSetOf<Activity>()
        private lateinit var appInstance: App

        @Synchronized
        @JvmStatic
        fun getInstance(): App {
            return appInstance
        }

        @JvmStatic
        fun addActivity(act: Activity) {
            allActivities.add(act)
        }

        @JvmStatic
        fun removeActivity(act: Activity) {
            allActivities.remove(act)
        }

        @JvmStatic
        fun removeActivity(cls: Class<*>) {
            synchronized(allActivities) {
                for (act in allActivities) {
                    if (act.javaClass == cls){
                        act.finish()
                    }
                }
            }
        }

        @JvmStatic
        fun currActivity():Activity {
            return allActivities.last()
        }

        @JvmStatic
        fun exitApp() {
            synchronized(allActivities) {
                for (act in allActivities) {
                    act.finish()
                }
            }
            Process.killProcess(Process.myPid())
        }

    }

    override fun onCreate() {
        super.onCreate()
        appInstance = this
        CrashReport.initCrashReport(getApplicationContext(), "9f172b973f", false);
        //添加公共请求头
        RxHttp.setOnParamAssembly { it.addHeader("Authorization", "${MyUtils.getToken()}") }
        RxHttp.setDebug(true)
        /**
         * 注意: 即使您已经在AndroidManifest.xml中配置过appkey和channel值，也需要在App代码中调
         * 用初始化接口（如需要使用AndroidManifest.xml中配置好的appkey和channel值，
         * UMConfigure.init调用中appkey和channel参数请置为null）。
         */
//        UMConfigure.init(this,"6074f00218b72d2d24510d62",null,0,null);
        UMConfigure.init(this, "6074f00218b72d2d24510d62",
            MyUtils.getUMChannelName(this), UMConfigure.DEVICE_TYPE_PHONE, "")
        UMConfigure.setLogEnabled(true);

        //腾讯IM
        if (!isSimulater) {
            DemoApplication.initLib(this)

            var configs = TUIKit.getConfigs();
            configs.setSdkConfig(V2TIMSDKConfig());
            configs.setCustomFaceConfig(CustomFaceConfig());
            configs.setGeneralConfig(GeneralConfig());
            TUIKit.init(this, 1400504311, configs);

            //注册监听
            var config = V2TIMSDKConfig()
            config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_INFO);
            V2TIMManager.getInstance().initSDK(this, 1400504311, config, object : V2TIMSDKListener() {
                override fun onConnecting() {
                    super.onConnecting()
                    LogUtils.e("正在连接腾讯云服务器");
                }

                override fun onConnectSuccess() {
                    super.onConnectSuccess()
                    LogUtils.e("连接腾讯云服务器成功");
                }

                override fun onConnectFailed(code: Int, error: String?) {
                    super.onConnectFailed(code, error)
                    LogUtils.e("连接腾讯云服务器失败");
                }

                override fun onKickedOffline() {
                    super.onKickedOffline()
                    LogUtils.e("当前用户被踢下线");

                    ToastUtils.showShort("您的账户已在另一处登录, 请重新登录")
                    SPUtils.getInstance().remove("token")
                    SPUtils.getInstance().remove("personinfo")
                    Router.newIntent(App.currActivity()).to(LoginActivity::class.java).launch()
                }

                override fun onUserSigExpired() {
                    super.onUserSigExpired()
                    LogUtils.e("登录票据已经过期");
                }
            })

        }
    }

}